<?php

namespace backend\controllers;

use yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

use backend\models\UploadForm;
use yii\web\UploadedFile;
use backend\models\Imgs;


class ServerController extends Controller {

    public $enableCsrfValidation = false;
    
    public function actionUploadImages()
    {
        $upload = new UploadForm();
        if (Yii::$app->request->isPost) {  
            $file = UploadedFile::getInstances($upload, 'file');  
            if(!$file){
                return $this->redirect('/tweet/images');
            }
            $basePath = yii\helpers\Url::to('@app');
            $base_url = Yii::$app->request->hostInfo;
            $filePath = $basePath.'/web/uploads/'.date("Ymd",time());
            if (!file_exists($filePath)){
                if(!mkdir($filePath,0777,true))
                {
                    Yii::$app->session->setFlash('error','上传失败！');  
                    return $this->redirect('/tweet/images');
                }
            }
            if ($file && $upload->validate()) {  
//                echo "<pre/>";  
                $i = 0;
                $file_arr = array();
                foreach ($file as $fl) {
                    $file_name = mt_rand(1100,9900) .time() .$fl->baseName. '.' . $fl->extension;
                    $path = $filePath.'/'.$file_name;
                    $res = $fl->saveAs($path); 
                    if($res){
                        $p = $base_url."/uploads/".date("Ymd",time()).'/'.$file_name;
                        $file_arr[] = $p;
                        $i++;
                    }
                }
                $img_res = Imgs::AddImages($file_arr);
                if($img_res){
                    Yii::$app->session->setFlash('success','上传成功！'.$i);  
                }else{
                    Yii::$app->session->setFlash('error','上传失败！');
                }
                return $this->redirect('/tweet/images');  
            }  
        }
    }

}
